package reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import reggie.common.R;
import reggie.dto.DishDto;
import reggie.entity.Category;
import reggie.entity.Dish;
import reggie.entity.DishFlavor;
import reggie.service.CategoryService;
import reggie.service.DishFlavorService;
import reggie.service.DishService;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * ClassName: DishFlavorController <br/>
 * Description: <br/>
 * date: 2022/12/2 16:11<br/>
 *
 * @author Xingyingsheng<br />
 * @since JDK 11
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {


    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;


    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("保存菜品===={}", dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("添加菜品成功");
    }


    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("查询菜品====");
//        构造分页构造器,dish中是缺少菜品分类的,要使用dishDto完成对数据的添加
        Page<Dish> pageInfo= new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        添加查询条件
//        添加排序条件
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
//        添加过滤条件
        lambdaQueryWrapper.like(name!=null,Dish::getName,name);
        dishService.page(pageInfo,lambdaQueryWrapper);
//        对象拷贝,除了records(list集合)中的数据,当前拷贝内容中仅有分页信息
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
//        获取查询出的数据
        List<Dish> records = pageInfo.getRecords();
//        通过操作records获取对应的菜品分类
        List<DishDto> list = records.stream().map((item) -> {
//            创建dishDto对象,接收原始数据
            DishDto dishDto = new DishDto();
//            从item中复制获得原始数据
            BeanUtils.copyProperties(item, dishDto);
//            获取原始数据中菜品的id
            Long categoryId = item.getCategoryId();
//            根据id查询分类对象
            Category category = categoryService.getById(categoryId);
//            根据Category获得菜品名称
            String ca = category.getName();
//            将名称传入dishDto对象中
            dishDto.setCategoryName(ca);
            return dishDto;
        }).collect(Collectors.toList());//收集对象至list集合中
//        将添加有菜品分类的集合传入dishDtoPage中
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){

        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("更新菜品===={}", dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        return R.success("更新菜品成功");
    }

    //停起售菜品
    @PostMapping("/status/{status}")
    public R<String> haltSalesControl(@PathVariable(value = "status") int status, @RequestParam(value = "ids") List<Long> ids){
        log.info("状态更改===ids：{},status:{}",ids,status);
//        String[] id = ids.split(",");
//        for (String s : id) {
//            LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//            lambdaQueryWrapper.eq(Dish::getId,Long.parseLong(s));
//            Dish dish = dishService.getOne(lambdaQueryWrapper);
//            dish.setStatus(status);
//            dishService.updateById(dish);
//        }
//        优化参数接收
        List<Dish> list = ids.stream().map(item -> {
            LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Dish::getId, item);
            Dish dish = dishService.getOne(lambdaQueryWrapper);
            dish.setStatus(status);
            return dish;
        }).collect(Collectors.toList());
        dishService.updateBatchById(list);

        return R.success("变更成功");
    }
    @DeleteMapping
    public R<String> delete(@RequestParam String ids){
        log.info("删除菜品：{}",ids);
        String[] id = ids.split(",");
        for (String s : id) {
            LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishLambdaQueryWrapper.eq(Dish::getId,Long.parseLong(s));
            dishLambdaQueryWrapper.eq(Dish::getStatus,1);//启售商品
            dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
            dishService.remove(dishLambdaQueryWrapper);
        }
        return R.success("菜品删除成功");
    }

//        @GetMapping("/list")
//    public R<List<Dish>> getListById(Dish dish){
//        log.info("查询菜品:{}",dish.toString());
//        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
//            List<Dish> list = dishService.list(lambdaQueryWrapper);
//            return R.success(list);
//        }
@GetMapping("/list")
public R<List<DishDto>> list(Dish dish){
    //构造查询条件
    LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
    //添加条件，查询状态为1（起售状态）的菜品
    queryWrapper.eq(Dish::getStatus,1);

    //添加排序条件
    queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

    List<Dish> list = dishService.list(queryWrapper);

    List<DishDto> dishDtoList = list.stream().map((item) -> {
        DishDto dishDto = new DishDto();

        BeanUtils.copyProperties(item,dishDto);

        Long categoryId = item.getCategoryId();//分类id
        //根据id查询分类对象
        Category category = categoryService.getById(categoryId);

        if(category != null){
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
        }

        //当前菜品的id
        Long dishId = item.getId();
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
        //SQL:select * from dish_flavor where dish_id = ?
        List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
        dishDto.setFlavors(dishFlavorList);
        return dishDto;
    }).collect(Collectors.toList());

    return R.success(dishDtoList);
}
}
